const app = require("express").Router();
const fs = require("fs");
var multiparty = require("multiparty");
const { Users, Friend } = require("../model/index");
const Sequelize = require("sequelize");
const Op = Sequelize.Op;

//导入创建token
const { createToken } = require("../utils/token");

// 注册用户
app.post("/register", (req, res) => {
  let params = req.body;
  if (!params.username) {
    res.json({ code: 1, msg: "请输入用户姓名" });
    return;
  }
  if (!params.password) {
    res.json({ code: 1, msg: "请输入密码" });
    return;
  }
  let data = {
    username: params.username,
    nick: params.nick,
    password: params.password,
    mobile: params.mobile,
    code: params.code,
    userid: "US" + Math.ceil(Math.random() * 10000000000),
  };
  // 检查是否被注册
  Users.findAndCountAll({
    where: {
      username: params.username,
    },
  })
    .then((ret) => {
      if (ret) {
        if (ret.rows && ret.rows[0]) {
          res.send({ code: -1, msg: "该账号被注册过" });
        } else {
          // 用户创建
          Users.create(data).then((ret) => {
            if (ret) {
              console.log(ret);
              res.send({ code: 0, msg: "注册成功！", data: ret });
            } else {
              res.send({ code: -1, msg: "注册失败！" });
            }
          });
        }
      } else {
        res.send({ code: -1, msg: "" });
      }
    })
    .catch((err) => {
      console.log(err);
      res.send({ code: -1, data: err });
    });
});

// 用户登录
app.post("/login", (req, res) => {
  let params = req.body;
  if (!params.username) {
    res.send({ code: 1, msg: "请输入用户姓名" });
    return;
  }
  if (!params.password) {
    res.send({ code: 1, msg: "请输入用户密码" });
    return;
  }
  Users.findAndCountAll({
    where: {
      username: params.username,
    },
  }).then((ret) => {
    if (ret && ret.rows[0]) {
      if (params.password == ret.rows[0].password) {
        if (ret.rows[0].status) {
          return res.send({
            code: 0,
            data: ret.rows[0],
            token: createToken({}, "24h"),
          });
        } else {
          return res.send({ code: -1, msg: "你已经被禁用" });
        }
      } else {
        return res.send({ code: -1, msg: "用户名或密码错误" });
      }
    } else {
      return res.send({ code: -1, msg: "用户名或密码错误" });
    }
  });
});

//  获取用户信息
app.get("/getUserInfo", (req, res) => {
  Users.findAndCountAll({
    where: {
      userid: req.query.userid,
    },
  }).then((ret) => {
    console.log(ret)
    if (ret && ret.rows[0]) {
      let data = ret.rows[0];
      delete data.password;
      console.log(data);
      res.send({ code: 0, data });
    } else {
      res.send({ code: -1, msg: "" });
    }
  });
});

// 修改用户
app.post("/edituser", (req, res) => {
  let params = req.body;
  Users.update(
    params,
    {
      where: {
        userid: params.userid,
      },
    }
  ).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: "修改成功" });
    } else {
      res.send({ code: -1, data: "修改失败" });
    }
  });
});


// 获取用户列表
app.get('/userlist', (req, res) => {
  const { nick, page } = req.query;
  let offset = (page - 1) * 10;
  if (!page) {
    res.send({ code: -1, msg: "页码未传" });
    return;
  }
  let where = {
    nick: {
      // 模糊查询
      [Op.like]: "%" + nick + "%",
    },
  };
  Users.findAndCountAll({
    limit: 100,
    offset,
    where
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '查询失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})


// 好友列表
// 添加好友
app.post('/addfriend', (req, res) => {
  Friend.create(req.body).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '请求失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})

// 同意好友请求
app.get('/agree', (req, res) => {
  Friend.update(req.body, {
    where: {
      userid: req.body.userid,
      status: req.body.status
    }
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '请求失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})


// 查询好友列表 通过的
app.get('/getfriend', (req, res) => {
  const { page } = req.query;
  let offset = (page - 1) * 10;
  if (!page) {
    res.send({ code: -1, msg: "页码未传" });
    return;
  }
  let where = {}
  if (req.query.status === '0' || req.query.status === '1') {
    where = {
      addid: req.query.addid,
      status: req.query.status,
    }
  } else {
    where = {
      userid: req.query.userid
    }
  }
  Friend.findAndCountAll({
    limit: 100,
    offset,
    where,
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '请求失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})

// 查询好友列表2 自己添加的
app.get('/getfriend2', (req, res) => {
  const { page } = req.query;
  let offset = (page - 1) * 10;
  if (!page) {
    res.send({ code: -1, msg: "页码未传" });
    return;
  }
  let where = {
    userid: req.query.userid,
    status: 1
  }
  Friend.findAndCountAll({
    limit: 100,
    offset,
    where,
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '请求失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})

// 查询申请消息
app.get('/getfriendnews', (req, res) => {
  const { page } = req.query;
  let offset = (page - 1) * 10;
  if (!page) {
    res.send({ code: -1, msg: "页码未传" });
    return;
  }
  Friend.findAndCountAll({
    limit: 100,
    offset,
    where: {
      addid: req.query.addid,
      status: 0
    }
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '请求失败' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})


// 同意好友
app.post('/agree', (req, res) => {
  Friend.update(req.body, {
    where: {
      id: req.body.id,
    }
  }).then(ret => {
    if (ret) {
      res.send({ code: 0, data: ret })
    } else {
      res.send({ code: -1, msg: '修改成功' })
    }
  }).catch(err => {
    res.send({ code: -1, msg: err })
  })
})




app.post("/uploadimg", (req, res) => {
  const form = new multiparty.Form(); // 表单 name
  form.encoding = "UTF-8"; // 设置编码
  form.uploadDir = "./assets"; // 设置临时文件中转站
  form.maxFilesSize = 2 * 1024 * 1024; // 2M  // 设置上传图片的最大内存
  form.parse(req, function (err, fields, files) {
    if (err) throw err; // fields 文件域对象        // files 图片文件
    var uploadUrl = "/images/";
    // file = files["instructions"]; // 图片信息
    if (files.file) {
      file = files.file; // 图片信息
      console.log(files, "files1");
    } else {
      file = files.filename;
      console.log(files, "files2");
    }
    var originalFilename, tempath;
    (originalFilename = file[0].originalFilename), // 1.jpg
      (tempath = file[0].path); // 临时的文件路径
    var timestamp = new Date().getTime();
    uploadUrl += timestamp + originalFilename; // /images/upload/12342314214521.jpg
    var newPath = "./public" + uploadUrl; // 最终的文件路径
    var fileRead = fs.createReadStream(tempath); // 可读流 可写流
    var fileWrite = fs.createWriteStream(newPath);
    fileRead.pipe(fileWrite); // pipe 管道输送 数据
    fileWrite.on("close", () => {
      // pipe 监听 关闭 删除临时文件夹里面的图片
      fs.unlinkSync(tempath);
      res.json({
        code: 0,
        msg: `http://139.186.153.243/node/public${uploadUrl}`,
      }); // msg uploadUrl
      // res.send({
      //   code:0,
      //   msg:`file:///C:/Users/Administrator/Desktop/my/node-app/public${uploadUrl}`
      // })


    });
  });
});





module.exports = app;
